//
//  PhotoAlbumViewController.m
//  WeCommunity
//
//  Created by mac on 2017/6/19.
//  Copyright © 2017年 lzy. All rights reserved.
//

#import "PhotoAlbumViewController.h"
#import "PhotoAlbumHelper.h"
#import "CustomPhotoAlbumCell.h"
#import "FullScreenImage.h"

#define ALBUMCOUNT 4 //相册一行展示几张
#define MAX_PHOTO_COUNT 9 //相册一次最多选取张数

@interface PhotoAlbumViewController ()<UITableViewDelegate,UITableViewDataSource,ChoosePhotoDelegate>

@property (nonatomic,strong) UIBarButtonItem * leftBtnItem;
@property (nonatomic,strong) UIBarButtonItem * rightBtnItem;
@property (nonatomic,strong) UITableView * tableView;
@property (nonatomic,strong) NSMutableArray * dataSource;
@property (nonatomic,strong) NSMutableArray * selectedDataSource;
@property (nonatomic,assign) NSInteger  selectedIndex;

@end

@implementation PhotoAlbumViewController

#pragma mark - get
-(UIBarButtonItem *)leftBtnItem
{
    if (!_leftBtnItem) {
        _leftBtnItem = [[UIBarButtonItem alloc] initWithTitle:KNSLocal(@"alertCancel") style:UIBarButtonItemStylePlain target:self action:@selector(cancel)];
        [_leftBtnItem setTitleTextAttributes:@{NSFontAttributeName:PFR_FONT(16), NSForegroundColorAttributeName :WHITE_COLOR} forState:UIControlStateNormal];
    }
    return _leftBtnItem;
}
-(UIBarButtonItem *)rightBtnItem
{
    if (!_rightBtnItem) {
        _rightBtnItem = [[UIBarButtonItem alloc] initWithTitle:KNSLocal(@"alertOK") style:UIBarButtonItemStylePlain target:self action:@selector(sure)];
        [_rightBtnItem setTitleTextAttributes:@{NSFontAttributeName:PFR_FONT(16), NSForegroundColorAttributeName :WHITE_COLOR} forState:UIControlStateNormal];
    }
    return _rightBtnItem;
}

-(UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.view.bounds),CGRectGetHeight(self.view.bounds) - 64) style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.backgroundColor = WHITE_COLOR;
        
    }
    return _tableView;
}

- (void)viewDidLoad {
    [super viewDidLoad];

    [self initWithUserInterface];
    
    [self loadingPhotosData];
}



-(void)initWithUserInterface
{
    self.navigationItem.leftBarButtonItem = self.leftBtnItem;
    self.navigationItem.rightBarButtonItem = self.rightBtnItem;
    [self setSureItemIsOk:NO count:0];
    [self.view addSubview:self.tableView];
    
}

#pragma mark - 加载相册数据
-(void)loadingPhotosData
{
    self.dataSource = [NSMutableArray array];
    self.selectedDataSource = [NSMutableArray array];
    
    @weakify(self);
    [[PhotoAlbumHelper shared] reloadingAllPicturesAndComplete:^(BOOL success, NSArray *results) {
        @strongify(self);
        if (success) {
            for (ALAsset * result in results) {
                PhotoAlbumModel * model = [PhotoAlbumModel new];
                model.asset = result ;
                model.selected = NO;
                model.canSelected = YES;
                model.selectedIndex = 0;
                
                [self.dataSource  addObject:model];
            }
            //如果有已经选择了的图片
            int i = 0;
            for (PhotoAlbumModel * oriModel in self.originalDataSource) {
                for (PhotoAlbumModel * nowModel in self.dataSource) {
                    if ([nowModel.assetUrl isEqualToString:oriModel.assetUrl]) {
                        i++;
                        nowModel.selected = YES;
                        nowModel.selectedIndex = i;
                        [self.selectedDataSource addObject:nowModel];
                    }
                }
            }
            
            [self setSureItemIsOk:self.selectedDataSource.count > 0 ? YES : NO count:self.selectedDataSource.count];
            //默认最多9张
            if (self.selectedDataSource.count >= self.maxPhotoCount) {
                for (PhotoAlbumModel * model in self.dataSource) {
                    model.canSelected = NO;
                }
                for (PhotoAlbumModel * model in self.selectedDataSource) {
                    model.canSelected = YES;
                }
            }else if (self.selectedDataSource.count < self.maxPhotoCount){
                for (PhotoAlbumModel * model in self.dataSource) {
                    model.canSelected = YES;
                }
            }
            [self.tableView reloadData];
            if (self.tableView.contentSize.height > self.view.frame.size.height){
                [self.tableView setContentOffset:CGPointMake(0, self.tableView.contentSize.height - self.tableView.bounds.size.height) animated:NO];
            }
        }else{
            //没有打开相册的权限
            [self systemAlertWithTitle:nil andMessage:KNSLocal(@"OpenPhotoAlbum") actionTextOne:KNSLocal(@"alertCancel") actionTextTwo:KNSLocal(@"alertOK") actionOneBlock:^{
                [self dismissBack];
            } actionTwoBlock:^{
                NSURL * url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
                [[UIApplication sharedApplication] openURL:url];
            }];
        }
    }];
}


#pragma mark - tableView delegate
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if ( self.dataSource.count % ALBUMCOUNT == 0) {
        return self.dataSource.count / ALBUMCOUNT;
    }else{
        return self.dataSource.count / ALBUMCOUNT + 1;
    }
    return 0;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return (KScreen_Width - 25) / 4 + 5;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString * cellID = @"albumCell";
    CustomPhotoAlbumCell * cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    if (!cell) {
        cell =[[CustomPhotoAlbumCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
    }
    cell.delegate = self;
    
    NSInteger index = indexPath.row * ALBUMCOUNT;
    NSInteger length = self.dataSource.count - index;
    if (length > 4) {
        length = 4;
    }

    NSMutableArray * tempArray = [NSMutableArray array];
    for (NSInteger i = index; i < index + length; i++) {
        PhotoAlbumModel * model = self.dataSource[i];
        [tempArray addObject:model];
    }
    
    [cell layoutViewWithModels:tempArray];
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}


#pragma mark - delegate
#pragma mark - 预览图片
-(void)preViewPhotoAlbum:(PhotoAlbumModel *)albumModel
{
    NSMutableArray * imageArray = [NSMutableArray array];
    
    //目前只支持选中的图片进行预览 加载大图太耗资源，以后有时间再优化
    if (albumModel.selected) {
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            for (PhotoAlbumModel * model in self.selectedDataSource) {
                if (!model.fullScreenImage) {
                    UIImage *image = [UIImage imageWithCGImage:[[model.asset defaultRepresentation] fullScreenImage]];
                    model.fullScreenImage = image;
                }
                FullScreenImage * imageModel = [FullScreenImage new];
                imageModel.fullImage = model.fullScreenImage;
                [imageArray addObject:imageModel];
            }
            dispatch_async(dispatch_get_main_queue(), ^{
                DealPhotosView * dealPhotosView = [[DealPhotosView alloc] init];
                [dealPhotosView setFullScreenWithImageArray:imageArray showIndex:albumModel.selectedIndex - 1];
                [[[UIApplication sharedApplication].delegate window] addSubview:dealPhotosView];
            });
        });
    }
}
-(void)choosePhotoAlbum:(PhotoAlbumModel *)albumModel sender:(UIButton *)sender
{
    sender.selected = !sender.selected;
    
    albumModel.selected = sender.selected;
    albumModel.canSelected = YES;
    
    if (sender.selected) {
        [self.selectedDataSource addObject:albumModel];
        //加载全屏大图会消耗时间，所以尽量早的去加载
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            if (!albumModel.fullScreenImage) {
                UIImage *image = [UIImage imageWithCGImage:[[albumModel.asset defaultRepresentation] fullScreenImage]];
                albumModel.fullScreenImage = image;
            }
        });
    }else{
        albumModel.selectedIndex = 0;
        [self.selectedDataSource  removeObject:albumModel];
    }
    int i = 0;
    for (PhotoAlbumModel * model in self.selectedDataSource) {
        i++;
        model.selectedIndex = i;
    }
    
    //默认最多9张
    if (self.selectedDataSource.count >= self.maxPhotoCount) {
        for (PhotoAlbumModel * model in self.dataSource) {
            model.canSelected = NO;
        }
        for (PhotoAlbumModel * model in self.selectedDataSource) {
            model.canSelected = YES;
        }
    }else if (self.selectedDataSource.count < self.maxPhotoCount){
        for (PhotoAlbumModel * model in self.dataSource) {
            model.canSelected = YES;
        }
    }

    [self setSureItemIsOk:self.selectedDataSource.count > 0 ? YES : NO count:self.selectedDataSource.count];
    
    [self.tableView reloadData];
}

#pragma mark - 确定
-(void)sure
{
    if (self.photoAlbumChooseBlock) {
        self.photoAlbumChooseBlock(self.selectedDataSource);
    }
    
    [self dismissBack];
}

-(void)cancel
{
    [self dismissBack];
}

-(void)dismissBack
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

-(void)photoAlbumChooseComplete:(PhotoAlbumChooseBlock)doneBlock
{
    self.photoAlbumChooseBlock = doneBlock;
}

-(void)setSureItemIsOk:(BOOL)ok count:(NSInteger)count
{
    if (ok) {
        self.rightBtnItem.enabled = YES;
        [self.rightBtnItem setTitleTextAttributes:@{NSFontAttributeName:PFR_FONT(16), NSForegroundColorAttributeName :WHITE_COLOR} forState:UIControlStateNormal];
    }else{
        self.rightBtnItem.enabled = NO;
        [self.rightBtnItem setTitleTextAttributes:@{NSFontAttributeName:PFR_FONT(16), NSForegroundColorAttributeName :[UIColor colorWithWhite:1.0 alpha:0.5]} forState:UIControlStateNormal];
    }
    
    if (count > 0) {
        self.rightBtnItem.title = [NSString stringWithFormat:@"%@(%ld)",KNSLocal(@"alertOK"),(long)count];
    }else{
        self.rightBtnItem.title = KNSLocal(@"alertOK");
    }
}

@end
